import { configure, start, done } from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import router from './router'
import { getToken, getRoles } from './utils/auth' // get token from cookie
import getPageTitle from './utils/get-page-title'
import store from '@/store'

configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/Xueyue'] // no redirect whitelist

let hasRoles = true
router.beforeEach(async (to: any, from: any, next) => {
  // start progress bar
  start()
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    // set page title
    document.title = getPageTitle(to.meta.title)
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      done()
    } else {
      const roles = await store.dispatch('user/getInfo') //获取登录用户的类型，及roles权限
      console.log(roles)
      const accessRoutes = await store.dispatch('permission/generateRoutes', roles.list)
      // console.log(accessRoutes)
      if (hasRoles) {
        accessRoutes.forEach((v: any) => {
          router.addRoute(v) //添加
        })
        hasRoles = false
        next({ ...to, replace: true })
      } else {
        //刷新时放行当前页面
        next()
      }
    }
  } else {
    // /* has no token*/白名单
    if (whiteList.includes(to.path)) {
      console.log(121)

      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next('/login')
      done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  done()
})
